package com.zhuoli.calendar;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Author: zhuoli
 * Description:
 * Date: 上午10:46 2018/6/14
 */
public class CalendarTest {

    void printCalendar(Calendar calendar) {

         /*date 表示时间和日期，输出：
         1. Unix 时间（毫秒）
         2. 格式化输出 yyyy-MM-dd HH:mm:ss*/
        System.out.println(String.format("%d -> %04d-%02d-%02d %02d:%02d:%02d", calendar.getTime().getTime(),
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DATE),
                calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)));
    }

    public void calendarTest() {
        /*当前时间*/
        Calendar calendar = Calendar.getInstance();
        printCalendar(calendar);


        calendar.setTime(new Date(12 * 1000L));
        /*输出：12000 -> 1970-01-01 08:00:12 注意是8点，因为Calendar使用了默认时区*/
        printCalendar(calendar);


         /*设置日期与时间 2018-06-14 00:00:00*/
        calendar.set(2018, Calendar.JUNE, 14, 0, 0, 0);
        /*输出：1528905600 -> 2018-06-14 00:00:00*/
        printCalendar(calendar);

        /*设置时区*/
        calendar.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
        /*输出：东京: 1528905600000 - Thu Jun 14 00:00:00 CST 2018*/
        System.out.println(String.format("东京: %d - %s", calendar.getTime().getTime(), calendar.getTime().toString()));
        /*输出：1528905600000 -> 2018-06-14 01:00:00*/
        printCalendar(calendar);

        calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        /*输出：上海: 1528905600000 - Thu Jun 14 00:00:00 CST 2018*/
        /*输出：1528905600000 -> 2018-06-14 00:00:00*/
        System.out.println(String.format("上海: %d - %s", calendar.getTime().getTime(), calendar.getTime().toString()));
        printCalendar(calendar);

        calendar.set(Calendar.SECOND, 30);
        /*输出：1528905630000 - Thu Jun 14 00:00:30 CST 2018*/
        System.out.println(String.format("%d - %s", calendar.getTime().getTime(), calendar.getTime().toString()));
        /*输出：1528905630000 -> 2018-06-14 00:00:30*/
        printCalendar(calendar);

        /*日期计算*/
        /*加30秒*/
        calendar.add(Calendar.MINUTE, 30);
        /*输出：1528907430000 -> 2018-06-14 00:30:30*/
        printCalendar(calendar);

        calendar.roll(Calendar.DATE, 1);
        /*加1天*/
        /*输出：1528993830000 -> 2018-06-15 00:30:30*/
        printCalendar(calendar);
    }

    public static void main(String[] args){
        CalendarTest calendarTest = new CalendarTest();
        calendarTest.calendarTest();
    }
}
